
package com.scs.application.modules.order.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.exceptions.ImportException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.ImportResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.BeanValidators;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.entity.HospitalMaterial;
import com.scs.application.modules.base.service.HospitalMaterialService;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.order.dto.DeliveryItemAddBySelectDTO;
import com.scs.application.modules.order.dto.DeliveryItemSplitDTO;
import com.scs.application.modules.order.entity.Delivery;
import com.scs.application.modules.order.entity.DeliveryItem;
import com.scs.application.modules.order.mapper.DeliveryMapper;
import com.scs.application.modules.order.request.DeliveryItemQueryRequest;
import com.scs.application.modules.order.service.DeliveryItemService;
import com.scs.application.modules.order.vo.DeliveryItemVO;
import lombok.AllArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 发货单明细 controller
 *
 */
@AllArgsConstructor
@RestController
@RequestMapping("/order/delivery_items")
public class DeliveryItemController extends CrudController<DeliveryItem, String, DeliveryItemService> implements ImAndExAbleController<DeliveryItemQueryRequest> {

    @Resource
    private HospitalMaterialService hospitalMaterialService;
    @Resource
    private DeliveryMapper deliveryMapper;

    @PostMapping
    public CommonResult add(@RequestBody @Valid DeliveryItem entity) {
        boolean bSave = service.saveDeliveryItemsById(entity);
        return bSave ? CommonResult.ok("新增成功", entity) : CommonResult.error("新增失败");
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid DeliveryItem entity) {
        boolean bUpdate = service.updateDeliveryItemsById(entity);
        return bUpdate ? CommonResult.ok("保存成功", entity) : CommonResult.error("保存失败");
    }

    @GetMapping("/page")
    public PageResult page(DeliveryItemQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(DeliveryItemQueryRequest request) {
        List<DeliveryItemVO> list = service.list(request);
        if (ObjectUtil.length(list) > 0) {
            List<String> matrCodeList = list.stream().filter(item -> StringUtils.isNotBlank(item.getMaterialCode())).map(DeliveryItemVO::getMaterialCode).distinct().collect(Collectors.toList());
            if (ObjectUtil.length(matrCodeList) > 0) {
                Map<String, HospitalMaterial> matrById = hospitalMaterialService.list(Wrappers.<HospitalMaterial>query().in("material_code",matrCodeList)).stream().collect(Collectors.toMap(HospitalMaterial::getMaterialCode, item -> item));
                for(DeliveryItemVO item: list) {
                    if (StringUtils.isNotBlank(item.getMaterialCode()) && matrById.containsKey(item.getMaterialCode())) {
                        item.setUdiSpec(matrById.get(item.getMaterialCode()).getUdi());
                    }
                }
            }
        }
        return CommonResult.ok("查询成功", list);
    }

    /**
     * @param children
     * @Description: 批量保存明细
     * @return: com.scs.application.core.model.CommonResult
     */
    @PutMapping("/batch_save")
    public CommonResult batchSave(@RequestBody @Valid @Validated List<DeliveryItem> children) {
        Assert.notEmpty(children, "至少有一条");
        BeanValidators.validateListWithException(validator, children);
        boolean bSuccess = service.saveOrUpdateBatchDtl(children);
        return bSuccess ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
    }

    @GetMapping("/surplus_order_item")
    public CommonResult surplusPurchaseOrder(Delivery delivery) {
        List<DeliveryItem> deliveryItemList = service.surplusPurchaseOrder(delivery);
        return CommonResult.ok("查询成功", deliveryItemList);
    }

    @Override
    @DeleteMapping({"/{id}"})
    public CommonResult deleteById(@PathVariable("id") String id) {
        boolean bRemove = this.service.deleteById(id);
        return bRemove ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
    }

    @GetMapping("/all_delivery_page")
    public PageResult allDeliveryPage(DeliveryItemQueryRequest request) {
        if(UserUtils.isHospital()) {
            request.setHospitalId(UserUtils.getHospitalId());
        } else {
            request.setSupplierId(UserUtils.getSupplierId());
        }
        IPage page = service.allDeliveryPage(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/export_delivery_items/{deliveryId}")
    public CommonResult getExportDeliveryItems(@PathVariable(name = "deliveryId") String deliveryId) {
        List<DeliveryItem> deliveryItems = service.getExportDeliveryItems(deliveryId);
        return CommonResult.ok("获取成功", deliveryItems);
    }

    @PostMapping("/excel/import/more")
    public CommonResult<ImportResult> excelImport(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws ImportException {
        Map<String, Object> maps = new HashMap<>();
        String deliveryIdKey = "deliveryId";
        maps.put(deliveryIdKey, request.getParameter(deliveryIdKey));
        return CommonResult.ok("导入成功", service.excelImport(file, maps));
    }


    /**
     * @description: 下载导入模板
     **/
    @GetMapping("/downloadExcelTemp/{deliveryId}")
    public void downloadExcelTemp(HttpServletResponse response,@PathVariable(name = "deliveryId") String deliveryId) {
        service.downloadExcelTemp(response,deliveryId);
    }


    @PostMapping("/importDtl")
    public CommonResult<ImportResult> importDtl(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws ImportException {
        return CommonResult.ok("导入成功", service.importDtl(file, request.getParameter("deliveryId")));
    }


    /**
     * @description: 发货明细拆分
     * @author: Tai
     * @date: 2024/10/15 12:13
     **/
    @PostMapping("/splitDtl")
    public CommonResult splitDtl(@RequestBody @Valid DeliveryItemSplitDTO entity) {
        return CommonResult.ok("操作成功",service.splitDtl(entity));
    }

    /***
     * @param request
     * @Description:  通用分页
     */
    @GetMapping("/pageCommon")
    public PageResult pageCommon(HttpServletRequest request,DeliveryItem entity) {
        IPage<DeliveryItem> page = QueryGenerator.parsePage(request);
        QueryWrapper<DeliveryItem> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        IPage<DeliveryItem> pageResult = service.page(page, queryWrapper);
        if (ObjectUtil.length(pageResult.getRecords()) > 0) {
            Delivery delivery = deliveryMapper.selectById(pageResult.getRecords().get(0).getDeliveryId());
            BusinessException.throwErrorIf(delivery==null, "发货单不存在，请刷新重试");

            List<String> matrCodeList = pageResult.getRecords().stream().filter(item -> StringUtils.isNotBlank(item.getMaterialCode())).map(DeliveryItem::getMaterialCode).distinct().collect(Collectors.toList());
            if (ObjectUtil.length(matrCodeList) > 0) {
                Map<String, HospitalMaterial> matrById = hospitalMaterialService.list(Wrappers.<HospitalMaterial>query()
                                .eq("hospital_id",delivery.getHospitalId())
                                .eq("supplier_id",delivery.getSupplierId())
                                .in("material_code",matrCodeList)).stream()
                        .collect(Collectors.toMap(HospitalMaterial::getMaterialCode, item -> item, (left, right) -> left));
                for(DeliveryItem item: pageResult.getRecords()) {
                    if (StringUtils.isNotBlank(item.getMaterialCode()) && matrById.containsKey(item.getMaterialCode())) {
                        item.setUdiSpec(matrById.get(item.getMaterialCode()).getUdi());
                    }
                }
            }
            for(DeliveryItem item: pageResult.getRecords()) {
                item.setUnitSelect(item.getUnit()).setOrderUnitSelect(item.getOrderUnit());
            }
        }
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * @Description:  批量保存发货明细，根据采购订单明细
     * @return: com.scs.application.core.model.CommonResult
     */
    @PutMapping("/addBySelect")
    public CommonResult addBySelect(@RequestBody @Valid  List<DeliveryItemAddBySelectDTO> children) {
        service.addBySelect(children);
        return CommonResult.ok() ;
    }
}
